package au.edu.unsw.editingtool.web;

import java.sql.SQLException;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import au.edu.unsw.editingtool.db.DBManager;
import au.edu.unsw.editingtool.global.EditingToolException;

/**
 * Application Lifecycle Listener implementation class sessionbindinglistener
 *
 */
public class SessionBindingListener implements HttpSessionBindingListener {

    /**
     * Default constructor. 
     */
	private String attribute;
	private String sessionid;
	private DBManager db;
	
    public SessionBindingListener(String attribute) {
        // TODO Auto-generated constructor stub
    	this.attribute = attribute;
    }

	/**
     * @see HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent)
     */
    public void valueUnbound(HttpSessionBindingEvent event) {
        // TODO Auto-generated method stub
    	try {
			this.dbUpdateTest();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (EditingToolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Value Unbinded");
    }

	/**
     * @see HttpSessionBindingListener#valueBound(HttpSessionBindingEvent)
     */
    public void valueBound(HttpSessionBindingEvent event) {
        // TODO Auto-generated method stub
    	this.sessionid = event.getSession().getId();
    	try {
			this.dbConnectTest();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	try {
			this.dbInsertTest();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (EditingToolException e) {
			e.printStackTrace();
		}
		System.out.println("Value binded");
    }
    
    private void dbConnectTest() throws ClassNotFoundException, SQLException{
    	db = new DBManager();
    	db.setDBHost("//129.94.181.38:3306/");
    	db.setDBSchema("editingtool");
    	db.setDBUser("editingtool");
    	db.setDBPassword("editingtool");
    	db.connDB();
    }
    
    private void dbInsertTest() throws SQLException, EditingToolException {
    	db.setTable("author", "");
    	db.setColumnValue("authorID", this.sessionid.substring(0, 15));
    	db.setColumnValue("lastName", "song");
    	db.setColumnValue("email", "songruoxin@unsw.edu.au");
    	db.insert(false, false);
    	db.cleanResource();
    }
    
	private void dbUpdateTest() throws SQLException, EditingToolException {
		db.setTable("author", "");
		db.setColumnValue("otherName", "ruoxin");
		db.setConditionString(" authorID = '" + this.sessionid.substring(0, 15) + "'");
		db.updateRecords();
		db.cleanResource();
	}
	
}
